package cc.android.testapp.xp.hooker;

import android.app.Application;

import java.lang.reflect.Method;
import java.util.Arrays;

import cc.android.testapp.cfg.CFG;
import cc.android.testapp.cfg.ConfigHelper;
import cc.android.testapp.util.CLog;
import cc.android.testapp.xp.HookBase;
import cc.android.testapp.xp.HookModule;
import cc.commons.util.reflect.MethodUtil;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XC_MethodReplacement;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage;

@HookModule(packages = "com.nokia.didang", name = "哑资源")
public class HookYaZIGuan extends HookBase implements ConfigHelper.IConfig {

    @CFG
    private boolean mIgnoreDis = false;

    @Override
    public String getCfgNode() {
        return "yzg";
    }

    @Override
    protected void hookToApp(XC_LoadPackage.LoadPackageParam pParam, Application pApp) throws Throwable {
        ClassLoader tLoader = pApp.getClassLoader();

        try {
            hookRootCheck(tLoader);
            hookDisCheck(tLoader);
            CLog.log("Hook YaZiGuan success");
        } catch (Throwable e) {
            CLog.log("Error on hook to YaZiGuan", e);
        }
    }

    private void hookRootCheck(ClassLoader pLoader) throws ClassNotFoundException {
        Class<?> tClazz;
        CLog.log("Prepare hook to YaZiGuan root");
        tClazz = pLoader.loadClass("com.nokia.common.utils.EmulatorUtils");

        Arrays.asList("isRoot", "isEmulator", "isFeatures", "notHasBlueTooth").forEach((method) ->
                XposedBridge.hookMethod(MethodUtil.getMethodIgnoreParam(tClazz, method, true).oneGet(),
                        XC_MethodReplacement.returnConstant(false)));

        CLog.log("hook to pda_root end !");
    }

    private void hookDisCheck(ClassLoader pLoader) throws ClassNotFoundException {
        Class<?> tClazz;
        CLog.log("Prepare hook to YaZiGuan dis check");
        tClazz = pLoader.loadClass("com.nokia.common.utils.Utils");

        Arrays.asList("checkPointCanUpdate", "checkPointCanUpdateLocation", "stopCheckPoint2LocationDistance",
                "checkDistance", "checkPoint2LocationDistanceNfc", "checkPointCanUpdate", "checkPoint2LocationDistance").forEach((method) ->
                XposedBridge.hookMethod(MethodUtil.getMethodIgnoreParam(tClazz, method, true).oneGet(), new XC_MethodHook() {
                    @Override
                    protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                        if (mIgnoreDis) param.setResult(true);
                    }
                }));

    }
}
